import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { ConfigProvider, theme, App } from 'antd';
import zhCN from 'antd/locale/zh_CN';

// 主题类型定义
export type ThemeType = 'light' | 'dark';

// 主题上下文类型
interface ThemeContextType {
  themeType: ThemeType;
  toggleTheme: () => void;
  setTheme: (theme: ThemeType) => void;
}

// 创建主题上下文
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

// 主题提供者组件
interface ThemeProviderProps {
  children: ReactNode;
}

export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
  // 从localStorage获取保存的主题，默认为浅色主题
  const [themeType, setThemeType] = useState<ThemeType>(() => {
    const savedTheme = localStorage.getItem('linkmate-theme') as ThemeType;
    return savedTheme || 'light';
  });

  // 切换主题
  const toggleTheme = () => {
    const newTheme = themeType === 'light' ? 'dark' : 'light';
    setThemeType(newTheme);
    localStorage.setItem('linkmate-theme', newTheme);
  };

  // 设置主题
  const setTheme = (theme: ThemeType) => {
    setThemeType(theme);
    localStorage.setItem('linkmate-theme', theme);
  };

  // 监听系统主题变化
  useEffect(() => {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    
    const handleChange = (e: MediaQueryListEvent) => {
      // 如果用户没有手动设置过主题，则跟随系统主题
      const savedTheme = localStorage.getItem('linkmate-theme');
      if (!savedTheme) {
        setThemeType(e.matches ? 'dark' : 'light');
      }
    };

    mediaQuery.addEventListener('change', handleChange);
    return () => mediaQuery.removeEventListener('change', handleChange);
  }, []);

  // 主题配置
  const themeConfig = {
    algorithm: themeType === 'dark' ? theme.darkAlgorithm : theme.defaultAlgorithm,
    token: {
      // 自定义主题色彩
      colorPrimary: '#1890ff',
      colorSuccess: '#52c41a',
      colorWarning: '#faad14',
      colorError: '#ff4d4f',
      colorInfo: '#1890ff',
      
      // 深色主题特殊配置
      ...(themeType === 'dark' && {
        colorBgContainer: '#141414',
        colorBgElevated: '#1f1f1f',
        colorBgLayout: '#000000',
        colorText: '#ffffff',
        colorTextSecondary: '#a6a6a6',
        colorBorder: '#303030',
        colorBorderSecondary: '#1f1f1f',
      }),
    },
    components: {
      Layout: {
        ...(themeType === 'dark' && {
          bodyBg: '#000000',
          headerBg: '#141414',
          siderBg: '#141414',
        }),
      },
      Card: {
        ...(themeType === 'dark' && {
          colorBgContainer: '#141414',
        }),
      },
      Menu: {
        ...(themeType === 'dark' && {
          colorBgContainer: '#141414',
          colorItemBg: 'transparent',
          colorItemBgSelected: '#1890ff',
          colorItemBgHover: '#1f1f1f',
        }),
      },
    },
  };

  const contextValue: ThemeContextType = {
    themeType,
    toggleTheme,
    setTheme,
  };

  return (
    <ThemeContext.Provider value={contextValue}>
      <ConfigProvider 
        locale={zhCN} 
        theme={themeConfig}
      >
        <App>
          {children}
        </App>
      </ConfigProvider>
    </ThemeContext.Provider>
  );
};

// 使用主题的Hook
export const useTheme = (): ThemeContextType => {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};

export default ThemeContext;
